package com.reggie.configuration.filter;

import com.alibaba.fastjson.JSON;
import com.reggie.configuration.common.LocalThread;
import com.reggie.configuration.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class AuthFilter implements Filter {
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    private static final Map<String, Integer> map = new HashMap<>();

    static {
        map.put("/backend/**", null);
        map.put("/front/**", null);
        map.put("/employee/login", null);
        map.put("/user/sendMsg", null);
        map.put("/user/login", null);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();    //为什么是URI？因为要拦截的是服务器内部资源


        //在这个里面的要么是静态资源要么是login，必须得放行了才可以login，所以要在这个if里面
        //需要用到ANT风格（就是/**路径之类的）的API

        // 放行匹配的url
        if (needAuth(requestURI)) {
            //如果这个判断成功了就放行

            if (antPathMatcher.match("/backend/**", requestURI)) {
                map.put("/backend/**", 1);
            }

            if (antPathMatcher.match("/user/login", requestURI)){
                map.put("/user/login",1);
            }

            //判断是否为前台页面
            if (antPathMatcher.match("/front/**", requestURI)) {
                map.put("/front/**", 1);
            }

            if (antPathMatcher.match("/employee/login", requestURI)){
                map.put("/employee/login",1);
            }

            filterChain.doFilter(request, response);
            return;
        }


//        if (antPathMatcher.match("/backend/**", requestURI) || antPathMatcher.match("/employee/**", requestURI) || antPathMatcher.match("/category/**", requestURI) || antPathMatcher.match("/order/**", requestURI) || antPathMatcher.match("/setmeal/**", requestURI) || antPathMatcher.match("/dish/**", requestURI)) {

            if (map.get("/employee/login") != null && map.get("/backend/**") != null) {
                //获得session域中的employee的ID
                // 如果登陆了,放行
                Long employeeID = (Long) request.getSession().getAttribute("employee");
                if (employeeID != null) {
                    log.info("职工已登录，职工id为：{}", request.getSession().getAttribute("employee"));
                    LocalThread.setEmployeeThread(employeeID);
                    filterChain.doFilter(request, response);
                    LocalThread.RemoveEmployeeThreadInfo();
                }
                return;
            }

//        }else {

            if (map.get("/user/login") != null || map.get("/front/**") != null) {
                //获得session域中的user的ID
                //判断User是否登陆了
                Long userId = (Long) request.getSession().getAttribute("user");
                if (userId != null) {
                    log.info("用户已登录，用户id为：{}", request.getSession().getAttribute("user"));
                    LocalThread.setUserThread(userId);
                    filterChain.doFilter(request, response);
                    LocalThread.RemoveUserThreadInfo();
                }
                return;
//            }

        }

        map.put("/employee/login", null);
        map.put("/backend/**", null);
        map.put("/user/login", null);
        map.put("/front/**", null);

        String UnLogin = JSON.toJSONString(Result.error("NOTLOGIN"));
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(UnLogin);
    }

    private boolean needAuth(String URI) {
        //我可以在这里加一个集合，如果是backend就附一个值，如果是front就附一个值，然后在上面判断，判断完立刻删除

       /* List<String> list = new ArrayList<>();
        list.add("/backend/**");
        list.add("/front/**");
        list.add("/employee/login");
        list.add("/user/sendMsg");
        list.add("/user/login");*/

        //判断是否为后台页面

        final Set<String> strings = map.keySet();
        for (String string : strings) {
            boolean match = antPathMatcher.match(string, URI);
            if (match) {
                return true;
            }
        }

        /*for (String pattern : list) {
            boolean match = antPathMatcher.match(pattern, URI);
            //这里就是一个一个判断了，不是就是false是了才是true
            if (match) {
                return true;
            }
        }*/

        return false;
    }

}
